Passed
Push — master ( 06c3b6...1fd195 )
by Dmytro
01:32
created

prettify.ts ➔ prettify   A

Complexity

Conditions 2

Size

Total Lines 16
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 16
c 0
b 0
f 0
rs 9.6
cc 2
1
import * as vscode from 'vscode';
2
import { LINE_SEPERATOR, TAB_SIZE } from '../constants';
3
import { commandDecorator } from './utils';
4
5
export const MESSAGES = {
6
    SUCCESS_MESSAGE : 'Logs prettified',
7
    ERROR_MESSAGE   : 'Error occured',
8
9
    EDITOR_NOT_FOUND : 'No editor found'
10
};
11
12
function parseJSONLine(line: string, index: number) {
13
    try {
14
        const json = JSON.parse(line);
15
16
        return JSON.stringify(json, null, TAB_SIZE);
17
    } catch (error) {
18
        console.error(`CANT_PARSE_LINE ${index}`);
19
        console.error(line);
20
        console.error(error);
21
22
        return line;
23
    }
24
}
25
26
export function prettify() {
27
    const editor = vscode.window.activeTextEditor;
28
29
    if (!editor) return console.error(MESSAGES.EDITOR_NOT_FOUND);
30
31
    const raw = editor.document.getText();
32
    const lines = raw.split(LINE_SEPERATOR);
33
    const modified = lines.map((line, index) => parseJSONLine(line, index));
34
35
    editor.edit(builder => {
36
        const firstLine = editor.document.lineAt(0);
37
        const lastLine = editor.document.lineAt(editor.document.lineCount - 1);
38
        const range = new vscode.Range(firstLine.range.start, lastLine.range.end);
39
40
        builder.replace(range, modified.join('\n'));
41
    });
42
}
43
44
export default commandDecorator(prettify, MESSAGES);
45